package app

import (
	DemoRouter "Demo_GoFrame/src/app/demo/router"
	LoveBirdRouter "Demo_GoFrame/src/app/loveBird/router"
	"Demo_GoFrame/src/common/configLoad"
	"Demo_GoFrame/src/common/utils"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"strconv"
)

type ServerAssemble struct {
	server      *ghttp.Server
	projectInfo configLoad.ProjectInfo
}

var allServers = make([]ServerAssemble, 0)

func StartServer() {
	configLoad.LoadProjects()
	//遍历需要启动的项目
	var appProjectArray = configLoad.GetAppProjectArray()
	var launchIDs = configLoad.GetLaunchIDs()
	for _, item := range appProjectArray {
		if isContainApp(launchIDs, strconv.Itoa(item.ID)) {
			assemble := ServerAssemble{}
			assemble.projectInfo = item
			log := g.Log(item.Name)
			log.SetPath(item.LogPath)
			log.SetStdoutPrint(true)
			switch item.ID {
			case 0:
				//demo
				assemble.server = DemoRouter.InitRouter(item)
				allServers = append(allServers, assemble)
				break
			case 1:
				//loveBird
				assemble.server = LoveBirdRouter.InitRouter(item)
				allServers = append(allServers, assemble)
				break
			}
		}
	}

	var finalServers = removeRepeatedElement(allServers)
	for _, assemble := range finalServers {
		if assemble.server != nil {
			assemble.server.SetRewrite("/favicon.ico", "/resource/image/favicon.ico")
			assemble.server.SetPort(assemble.projectInfo.Port)
			assemble.server.SetConfigWithMap(g.Map{
				"Address":    ":" + strconv.Itoa(assemble.projectInfo.Port),
				"ServerRoot": utils.GetCurrentPath() + "/" + assemble.projectInfo.ServerRoot,
			})
			assemble.server.BindMiddlewareDefault(GlobalCORS)
			assemble.server.Start()
		}
	}

	g.Wait()
}

func isContainApp(srcArray []string, target string) bool {
	for _, eachItem := range srcArray {
		if eachItem == target {
			return true
		}
	}
	return false
}

//去重
func removeRepeatedElement(arr []ServerAssemble) (newArr []ServerAssemble) {
	newArr = make([]ServerAssemble, 0)
	for i := 0; i < len(arr); i++ {
		repeat := false
		for j := i + 1; j < len(arr); j++ {
			if arr[i].server == arr[j].server {
				repeat = true
				break
			}
		}
		if !repeat {
			newArr = append(newArr, arr[i])
		}
	}
	return
}
